package com.graphite.http;


import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;

/**
 *
 */
public class HttpClientPool {
    private static Logger logger = LoggerFactory.getLogger(HttpClientPool.class);
    private static PoolingHttpClientConnectionManager cm = null;

    public HttpClientPool() {
    }

    public static CloseableHttpClient getHttpClient() {
        long startTime = System.currentTimeMillis();
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
        long endTime = System.currentTimeMillis();
        logger.info("HttpClientPool.getHttpClient耗时（毫秒）：" + (endTime - startTime));
        return client;
    }

    static {
        SSLConnectionSocketFactory sslsf = null;
        try {
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException var2) {
            var2.printStackTrace();
        }
        RegistryBuilder<ConnectionSocketFactory> connectionSocketFactoryRegistryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
        RegistryBuilder<ConnectionSocketFactory> https = connectionSocketFactoryRegistryBuilder.register("https", sslsf);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = https.register("http", new PlainConnectionSocketFactory()).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(500);
        cm.setDefaultMaxPerRoute(50);
    }
}
